<template>
  <view class="container">
    <view class="header">
      <text class="title">全国订单分布热点图</text>
    </view>
    
    <view class="map-container">
      <map 
        class="map"
        :latitude="mapCenter.latitude"
        :longitude="mapCenter.longitude"
        :scale="4"
        show-location
        :markers="markers"
        @regionchange="onRegionChange"
        @markertap="onMarkerTap"  
      ></map>
      
      <!-- 弹窗组件：显示订单数量 -->
      <view 
        class="popup" 
        v-if="showPopup"
        :style="{ top: popupTop + 'px', left: popupLeft + 'px' }"
      >
        <view class="popup-arrow"></view>
        <view class="popup-content">
          <text class="province">{{ currentProvince }}</text>
          <text class="count">订单数量：{{ currentOrderNum }}单</text>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      mapCenter: {
        latitude: 35.86166,
        longitude: 104.195397
      },
      markers: [],
      isMoving: false,
      // 新增：弹窗相关数据
      showPopup: false,       // 是否显示弹窗
      currentProvince: '',    // 当前点击的省份
      currentOrderNum: 0,     // 当前点击的订单数量
      popupTop: 0,            // 弹窗顶部位置
      popupLeft: 0            // 弹窗左侧位置
    };
  },
  onLoad() {
    this.fetchOrderData();
  },
  methods: {
    onRegionChange(e) {
      this.isMoving = e.type === 'begin';
      // 地图移动时关闭弹窗
      if (this.isMoving) {
        this.showPopup = false;
      }
    },
    
    // 新增：标记点点击事件处理
    onMarkerTap(e) {
		console.log(e)
      // 获取点击的标记点数据
      const markerId = e.markerId.toString(); // 转换为字符串以便匹配
      
      // 查找对应的订单数据
      const orderItem = this.orderData.find(item => item.code === markerId);
	  console.log(orderItem)
      if (orderItem) {
        this.currentProvince = orderItem.province;
        this.currentOrderNum = parseInt(orderItem.order_num);
        
        // 计算弹窗位置（基于点击坐标）
        this.popupLeft = e.detail.x - 80;  // 居中调整
        this.popupTop = e.detail.y - 120;  // 显示在点击位置上方
        
        // 显示弹窗
        this.showPopup = true;
		uni.showToast({
			title:`${this.currentProvince}:${this.currentOrderNum}`,
			icon:'none'
		})
      }
    },
    
    fetchOrderData() {
      // 保存原始数据用于点击事件查询
      this.orderData = [
        { "province": "北京市", "code": "110000", "order_num": "0" },
        { "province": "天津市", "code": "120000", "order_num": "0" },
        { "province": "河北省", "code": "130000", "order_num": "0" },
        { "province": "山西省", "code": "140000", "order_num": "1" },
        { "province": "内蒙古自治区", "code": "150000", "order_num": "0" },
        { "province": "辽宁省", "code": "210000", "order_num": "20" },
        { "province": "湖北省", "code": "420000", "order_num": "2" },
        { "province": "陕西省", "code": "610000", "order_num": "4" },
        // 其他省份数据...
      ];
      this.initMarkers(this.orderData);
    },
    
    initMarkers(orderData) {
      const provinceCenters = {
      	"110000": {
      		latitude: 39.9042,
      		longitude: 116.4074
      	}, // 北京
      	"120000": {
      		latitude: 39.0842,
      		longitude: 117.2009
      	}, // 天津
      	"130000": {
      		latitude: 38.0371,
      		longitude: 114.5149
      	}, // 河北
      	"140000": {
      		latitude: 37.8705,
      		longitude: 112.5497
      	}, // 山西
      	"150000": {
      		latitude: 40.8173,
      		longitude: 111.6580
      	}, // 内蒙古
      	"210000": {
      		latitude: 41.8055,
      		longitude: 123.4289
      	}, // 辽宁
      	"220000": {
      		latitude: 43.8868,
      		longitude: 125.3245
      	}, // 吉林
      	"230000": {
      		latitude: 45.8038,
      		longitude: 126.5348
      	}, // 黑龙江
      	"310000": {
      		latitude: 31.2304,
      		longitude: 121.4737
      	}, // 上海
      	"320000": {
      		latitude: 32.0603,
      		longitude: 118.7969
      	}, // 江苏
      	"330000": {
      		latitude: 30.2741,
      		longitude: 120.1551
      	}, // 浙江
      	"340000": {
      		latitude: 31.8611,
      		longitude: 117.2854
      	}, // 安徽
      	"350000": {
      		latitude: 26.0990,
      		longitude: 119.2959
      	}, // 福建
      	"360000": {
      		latitude: 28.6824,
      		longitude: 115.8570
      	}, // 江西
      	"370000": {
      		latitude: 36.6512,
      		longitude: 117.1200
      	}, // 山东
      	"410000": {
      		latitude: 34.7472,
      		longitude: 113.6250
      	}, // 河南
      	"420000": {
      		latitude: 30.5928,
      		longitude: 114.3055
      	}, // 湖北
      	"430000": {
      		latitude: 28.1125,
      		longitude: 112.9834
      	}, // 湖南
      	"440000": {
      		latitude: 23.1291,
      		longitude: 113.2644
      	}, // 广东
      	"450000": {
      		latitude: 22.8170,
      		longitude: 108.3665
      	}, // 广西
      	"460000": {
      		latitude: 20.0444,
      		longitude: 110.3497
      	}, // 海南
      	"500000": {
      		latitude: 29.4316,
      		longitude: 106.9123
      	}, // 重庆
      	"510000": {
      		latitude: 30.6570,
      		longitude: 104.0650
      	}, // 四川
      	"520000": {
      		latitude: 26.5784,
      		longitude: 106.7135
      	}, // 贵州
      	"530000": {
      		latitude: 25.0453,
      		longitude: 102.7186
      	}, // 云南
      	"540000": {
      		latitude: 29.6500,
      		longitude: 91.1000
      	}, // 西藏
      	"610000": {
      		latitude: 34.3416,
      		longitude: 108.9398
      	}, // 陕西
      	"620000": {
      		latitude: 36.0611,
      		longitude: 103.8343
      	}, // 甘肃
      	"630000": {
      		latitude: 36.6172,
      		longitude: 101.7797
      	}, // 青海
      	"640000": {
      		latitude: 38.4861,
      		longitude: 106.2323
      	}, // 宁夏
      	"650000": {
      		latitude: 43.8256,
      		longitude: 87.6168
      	}, // 新疆
      	"710000": {
      		latitude: 25.0389,
      		longitude: 121.5200
      	}, // 台湾
      	"810000": {
      		latitude: 22.2784,
      		longitude: 114.1654
      	}, // 香港
      	"820000": {
      		latitude: 22.1987,
      		longitude: 113.5491
      	} // 澳门
      };
      
      this.markers = orderData
        .filter(item => parseInt(item.order_num) > 0)
        .map(item => {
          const center = provinceCenters[item.code];
          if (!center) return null;
          
          const orderNum = parseInt(item.order_num);
          const style = this.getMarkerStyle(orderNum);
          
          return {
            id: parseInt(item.code),
            latitude: center.latitude,
            longitude: center.longitude,
            iconPath: this.createHeatIcon(style.color, style.size),
            width: style.size,
            height: style.size,
            // 添加点击事件相关的自定义数据
            customCallout: {
              display: 'BYCLICK'  // 点击显示（可选，也可使用自定义弹窗）
            }
          };
        })
        .filter(marker => marker !== null);
    },
    
    getMarkerStyle(orderNum) {
      if (orderNum >= 10) {
        return { color: '#ff3b30', size: 40 };  // 红色标记
      } else if (orderNum >= 5) {
        return { color: '#ff9500', size: 30 };  // 橙色标记
      } else if (orderNum >= 1) {
        return { color: '#ffcc00', size: 20 };  // 黄色标记
      }
      return { color: '#4cd964', size: 15 };
    },
    
    // Base64编码实现（保持不变）
    base64Encode(str) {
      const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
      let output = '';
      let chr1, chr2, chr3, enc1, enc2, enc3, enc4;
      let i = 0;
      
      str = this.utf8Encode(str);
      
      while (i < str.length) {
        chr1 = str.charCodeAt(i++);
        chr2 = i < str.length ? str.charCodeAt(i++) : 0;
        chr3 = i < str.length ? str.charCodeAt(i++) : 0;
        
        enc1 = chr1 >> 2;
        enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
        enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
        enc4 = chr3 & 63;
        
        if (isNaN(chr2)) {
          enc3 = enc4 = 64;
        } else if (isNaN(chr3)) {
          enc4 = 64;
        }
        
        output = output +
          chars.charAt(enc1) + chars.charAt(enc2) +
          chars.charAt(enc3) + chars.charAt(enc4);
      }
      
      return output;
    },
    
    utf8Encode(str) {
      str = str.replace(/\r\n/g, '\n');
      let utftext = '';
      
      for (let n = 0; n < str.length; n++) {
        const c = str.charCodeAt(n);
        
        if (c < 128) {
          utftext += String.fromCharCode(c);
        } else if ((c > 127) && (c < 2048)) {
          utftext += String.fromCharCode((c >> 6) | 192);
          utftext += String.fromCharCode((c & 63) | 128);
        } else {
          utftext += String.fromCharCode((c >> 12) | 224);
          utftext += String.fromCharCode(((c >> 6) & 63) | 128);
          utftext += String.fromCharCode((c & 63) | 128);
        }
      }
      
      return utftext;
    },
    
    createHeatIcon(color, size) {
      const svg = `
        <svg xmlns="http://www.w3.org/2000/svg" width="${size}" height="${size}">
          <circle cx="${size/2}" cy="${size/2}" r="${size/2 - 2}" fill="${color}" fill-opacity="0.6"/>
          <circle cx="${size/2}" cy="${size/2}" r="${size/3}" fill="${color}" fill-opacity="0.8"/>
          <circle cx="${size/2}" cy="${size/2}" r="${size/6}" fill="${color}"/>
        </svg>
      `;
      
      return `data:image/svg+xml;base64,${this.base64Encode(svg)}`;
    }
  }
};
</script>

<style scoped>
page {
  overflow: hidden;
  height: 100%;
}

.container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #f5f5f5;
  overflow: hidden;
}

.header {
  padding: 16px;
  text-align: center;
  background-color: #fff;
  border-bottom: 1px solid #eee;
}

.title {
  font-size: 18px;
  font-weight: 600;
  color: #333;
}

.map-container {
  flex: 1;
  position: relative;
  overflow: hidden;
}

.map {
  width: 100%;
  height: 100%;
}

/* 弹窗样式 */
.popup {
  position: absolute;
  z-index: 999;
  width: 160px;
}

.popup-arrow {
  width: 0;
  height: 0;
  margin: 0 auto;
  border-left: 8px solid transparent;
  border-right: 8px solid transparent;
  border-top: 8px solid #fff;
}

.popup-content {
  padding: 10px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.15);
}

.province {
  display: block;
  font-size: 16px;
  font-weight: bold;
  color: #333;
  margin-bottom: 5px;
}

.count {
  display: block;
  font-size: 14px;
  color: #666;
}
</style>
    